﻿using System;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;

namespace pdf_extract
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename2 = @"d:\temp\1.pdf";

            PdfReader reader = new PdfReader(filename2);
            PdfReaderContentParser parser = new PdfReaderContentParser(reader);

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                var fname = string.Format(@"d:\temp\jpg\{0}.jpg", i.ToString());

                IPIRMISRenderListener listener = new IPIRMISRenderListener(fname);
                parser.ProcessContent(i, listener);
            }

            Console.ReadKey();
        }
    }

    class IPIRMISRenderListener : IRenderListener
    {
        protected string Path;

        public IPIRMISRenderListener(string path)
        {
            this.Path = path;
        }

        public void BeginTextBlock()
        {
        }

        public void EndTextBlock()
        {
        }

        public void RenderImage(ImageRenderInfo renderInfo)
        {
            try
            {
                PdfImageObject img = renderInfo.GetImage();
                var filetype = img.GetFileType();
                byte[] bytes = null;
                if (filetype.Equals("jbig2"))
                {
                    var x = new JBig2Decoder.JBIG2StreamDecoder();
                    bytes = x.decodeJBIG2(img.GetImageAsBytes());

                }
                else
                {
                    bytes = img.GetImageAsBytes();
                }

                using (var stream = new System.IO.FileStream(this.Path , System.IO.FileMode.CreateNew))
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        public void RenderText(TextRenderInfo renderInfo)
        {
        }
    }


}
